I'm looking for a quick and easy way to preload images with JavaScript. I'm using jQuery if that's important.
I saw this here (http://nettuts.com...):
我再找快速方便的方式來預載圖片,我主要是用jQuery如果這重要的話
function complexLoad(config, fileNames) {
for (var x = 0; x < fileNames.length; x++) {
$("<img>").attr({
id: fileNames[x],
src: config.imgDir + fileNames[x] + config.imgFormat,
title: "The " + fileNames[x] + " nebula"
}).appendTo("#" + config.imgContainer).css({ display: "none" });
}
};
But, it looks a bit over-the-top for what I want!
I know there are jQuery plugins out there that do this but they all seem a bit big (in size); I just need a quick, easy and short way of preloading images!
但是這個感覺有點太過頭太多了一點,
我知道有一些jQuery插件可以做得到,但是他們都感覺有點太大,我想找更快速簡潔的方式
Quick and easy:
快速簡潔:
function preload(arrayOfImages) {
$(arrayOfImages).each(function(){
$('<img/>')[0].src = this;
// Alternatively you could use:
// (new Image()).src = this;
});
}
// Usage:
preload([
'img/imageName.jpg',
'img/anotherOne.jpg',
'img/blahblahblah.jpg'
]);
Or, if you want a jQuery plugin:
如果你享用jQuery插件的話:
$.fn.preload = function() {
this.each(function(){
$('<img/>')[0].src = this;
});
}
// Usage:
$(['img1.jpg','img2.jpg','img3.jpg']).preload();